package 多线程07_线程池;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Java 单线程和线程池耗时的对比
 * @ClassName: TestThread01
 * @Author: AllenSun
 * @Date: 2022/3/18 上午1:46
 */
public class TestThread04 {
    public static void main(String[] args) throws InterruptedException {
        // singleThread();
        threadPool();
    }


    public static void singleThread() throws InterruptedException {
        Long startTime = System.currentTimeMillis();
        final Random random = new Random();
        final List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            /*new Thread(() ->{
                list.add(random.nextInt());
            }).start();*/
            Thread thread = new Thread() {
                public void run() {
                    list.add(random.nextInt());
                }
            };
            thread.start();
            thread.join();

        }
        System.out.println("时间："+(System.currentTimeMillis()-startTime));
        System.out.println("大小："+list.size());
    }

    public static void threadPool() throws InterruptedException {
        Long startTime = System.currentTimeMillis();
        final Random random = new Random();
        final List<Integer> list = new ArrayList<>();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 100000; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    list.add(random.nextInt());
                }
            });

        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
        System.out.println("时间："+(System.currentTimeMillis()-startTime));
        System.out.println("大小："+list.size());
    }

}
